import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPServer {
    private ServerSocket listenSocket = null;
    public TCPServer(int pork) throws IOException {
        listenSocket = new ServerSocket(pork);
    }
    private void start() throws IOException, InterruptedException {
        System.out.println("服务器启动");
        while (true){
            System.out.println("==");
            if (listenSocket.isClosed()){
                Thread.sleep(5000);
                break;
            }
            Socket clientSocket = listenSocket.accept();
            System.out.println("======");
            server(clientSocket);
        }
    }

    private void server(Socket clientSocket) throws IOException, InterruptedException {
        System.out.println("客户端上线");
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            while (true){
                //读取客户端请求
                Thread.sleep(1500);
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNext()){
                    System.out.println("当前客户端下线");
                    break;
                }
                String request = scanner.next();
                //响应函数
                String response = responseFun(request);
                //发送响应
                System.out.println(response);
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();
                String log = String.format("%s:%s,%s,%s",clientSocket.getInetAddress().toString(),
                                                                clientSocket.getPort(),request,response);
                System.out.println(log);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            listenSocket.close();
        }
    }

    private String responseFun(String request) {
        return request + "嘎嘎";
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        TCPServer tcpServer = new TCPServer(9999);
        tcpServer.start();
    }
}
